package com.weiya.commons.exception;

import com.weiya.commons.enums.EnumInterface;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;

/**
 * BizException 业务异常
 *
 * @author qingzhi
 * @date 2017-10-11
 */
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@Getter
@Setter(AccessLevel.PRIVATE)
public class BizException extends RuntimeException implements ExceptionInterface {

    @NonNull
    private Integer code;

    @NonNull
    private String msg;

    private BizException(Integer code, String msg) {
        super(msg);
        this.code = code;
        this.msg = msg;
    }

    private static BizException of(Integer code, String msg) {
        return new BizException(code, msg);
    }

    /**
     * @param error 错误码枚举
     */
    public static BizException create(@NonNull EnumInterface error) {
        return BizException.of(error.getCode(), error.getDesc());
    }

    /**
     * @param error 错误码
     * @param errorMessage 自定义错误信息
     */
    public static BizException create(@NonNull EnumInterface error, @NonNull String errorMessage) {
        if (StringUtils.isBlank(errorMessage)) {
            return BizException.of(error.getCode(), error.getDesc());
        }
        return BizException.of(error.getCode(), errorMessage);
    }
}